package com.nnnu.wsnackshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nnnu.wsnackshop.exception.ObjectException;
import com.nnnu.wsnackshop.pojo.dto.ActivityLogPageDTO;
import com.nnnu.wsnackshop.pojo.entity.ActivityLogs;
import com.nnnu.wsnackshop.mapper.ActivityLogsMapper;
import com.nnnu.wsnackshop.pojo.vo.ActivityLogVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.service.IActivityLogsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台日志 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@RequiredArgsConstructor
public class ActivityLogsServiceImpl extends ServiceImpl<ActivityLogsMapper, ActivityLogs> implements IActivityLogsService {


    private static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public PageResult<ActivityLogVO> pageLogs(@NotNull ActivityLogPageDTO dto) {
        Page<ActivityLogs> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        LambdaQueryWrapper<ActivityLogs> qw = new LambdaQueryWrapper<ActivityLogs>()
                .eq(dto.getUserId() != null, ActivityLogs::getUserId, dto.getUserId())
                .like(dto.getAction() != null && !dto.getAction().isBlank(), ActivityLogs::getAction, dto.getAction())
                .orderByDesc(ActivityLogs::getCreatedAt);
        if (dto.getStartDate() != null) {
            qw.ge(ActivityLogs::getCreatedAt, dto.getStartDate().atStartOfDay());
        }
        if (dto.getEndDate() != null) {
            qw.le(ActivityLogs::getCreatedAt, dto.getEndDate().atTime(23, 59, 59));
        }

        Page<ActivityLogs> result = baseMapper.selectPage(page, qw);

        List<ActivityLogVO> vos = result.getRecords().stream().map(log -> {
            ActivityLogVO vo = BeanUtil.toBean(log, ActivityLogVO.class);
            vo.setCreatedAt(log.getCreatedAt().format(FMT));
            return vo;
        }).collect(Collectors.toList());

        return PageResult.<ActivityLogVO>builder()
                .total(result.getTotal())
                .items(vos)
                .build();
    }

    @Override
    public ActivityLogVO getLogDetail(Long id) {
        ActivityLogs log = baseMapper.selectById(id);
        if (log == null) {
            throw new ObjectException("日志不存在: " + id);
        }
        ActivityLogVO vo = BeanUtil.toBean(log, ActivityLogVO.class);
        vo.setCreatedAt(log.getCreatedAt().format(FMT));
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteLogs(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ObjectException("待删除日志ID列表不能为空");
        }
        // 校验
        List<Long> missing = ids.stream()
                .distinct()
                .filter(id -> baseMapper.selectById(id) == null)
                .toList();
        if (!missing.isEmpty()) {
            throw new ObjectException("以下日志不存在，无法删除: " + missing);
        }
        // 批量删除cs
        baseMapper.deleteBatchIds(ids);
    }
}
